/******************************************************************
 *
 *    Java Lib For JavaWeb, Powered By Shenzhen WEI YI KE JI .
 *
 *    Copyright (c) 2017-2027 Digital Telemedia Co.,Ltd
 *    http://www.d-telemedia.com/
 *
 *    Package:     com.theyeasy.dvmini.service.impl
 *
 *    Filename:    ProjectServiceImpl.java
 *
 *    Description: TODO(用一句话描述该文件做什么)
 *
 *    Copyright:   Copyright (c) 2017-2027
 *
 *    Company:     Theyeasy Telemedia Co.,Ltd
 *
 *    @author:     hm
 *
 *    @version:    1.0.0
 *
 *    Create at:   2017年10月22日 下午5:53:36
 *
 *    Revision:
 *
 *    2017年10月22日 下午5:53:36
 *        - first revision
 *
 *****************************************************************/
package com.theyeasy.dvmini.service.impl;

import java.io.InputStream;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.theyeasy.weixin.service.WxOpenService;
import org.theyeasy.weixin.util.WxMiniUtil;

import com.google.common.base.Strings;
import com.theyeasy.dvmini.dao.ChatlogDao;
import com.theyeasy.dvmini.dao.FansDao;
import com.theyeasy.dvmini.dao.ProjectDao;
import com.theyeasy.dvmini.dao.SalesDao;
import com.theyeasy.dvmini.enums.ChatLogReplyType;
import com.theyeasy.dvmini.model.Chatlog;
import com.theyeasy.dvmini.model.Fans;
import com.theyeasy.dvmini.model.Projects;
import com.theyeasy.dvmini.model.Sales;
import com.theyeasy.dvmini.service.FansService;
import com.theyeasy.dvmini.service.PosterService;
import com.theyeasy.dvmini.service.ProjectService;
import com.theyeasy.dvmini.service.SalesService;
import com.theyeasy.dvmini.util.CommonUtil;
import com.theyeasy.dvmini.util.PageResults;
import com.theyeasy.dvmini.util.ReadExcel;
import com.theyeasy.dvmini.util.RedisUtil;
import com.theyeasy.dvmini.util.StringUtil;
import com.theyeasy.dvmini.vo.ExcelSales_Vo;
import com.theyeasy.dvmini.vo.SalesReport_Vo;
import com.theyeasy.dvmini.vo.Sales_Vo;
import com.theyeasy.dvmini.vo.Vo_msg;

import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @ClassName ProjectServiceImpl
 * @Description TODO(这里用一句话描述这个类的作用)
 * @author hm
 * @Date 2017年10月22日 下午5:53:36
 * @version 1.0.0
 */
@Service
public class SalesServiceImpl implements SalesService {

	@Autowired
	SalesDao saleDao;

	@Autowired
	ProjectDao projectDao;

	@Autowired
	ProjectService projectService;

	@Autowired
	PosterService posterService;

	@Autowired
	WxOpenService wxOpenService;

	@Autowired
	FansService fansService;

	@Autowired
	FansDao fansDao;

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.SalesService#getSalesList(java.lang.Integer,
	 * java.lang.String)
	 */
	@Override
	public PageResults<Sales_Vo> getSalesList(Integer page, Integer pagesize,String keyword, Integer projectid, Boolean isvanker) {

	    if(StringUtil.isZearoOrNull(pagesize))pagesize=10;
		List<Sales_Vo> list = saleDao.getSalesList((page - 1) * pagesize, pagesize, projectid, keyword, isvanker);
		int total = saleDao.getSalesCount(projectid, keyword, isvanker);
		PageResults<Sales_Vo> pageresult = new PageResults<>();
		pageresult.setPage(page);
		pageresult.setPageSize(pagesize);
		pageresult.setRows(list);
		pageresult.setTotal(total);
		return pageresult;
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.SalesService#addSales(java.lang.String,
	 * java.lang.String, java.lang.Integer)
	 */
	@Override
	public String addSales(String name, String phone, Integer projectid, Boolean isValid, Boolean isVanker) {

		// 判断销售是否已存在
		Example example = new Example(Sales.class);
		example.createCriteria().andEqualTo("phone", phone).andEqualTo("deleted", false);
		if (saleDao.selectCountByExample(example) > 0)
			return "添加失败，该销售人员手机已存在";

		Sales sale = new Sales();
		sale.setName(name);
		sale.setPhone(phone);
		sale.setProjectid(projectid);
		sale.setDeleted(false);
		sale.setUpdatedtime(CommonUtil.getTime());
		sale.setIsvalid(isValid);
		sale.setIsvanker(isVanker);
		int row = saleDao.insertSelective(sale);
		return row > 0 ? "ok" : "添加失败，数据异常";
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.SalesService#updateSales(java.lang.Integer,
	 * java.lang.String, java.lang.String, java.lang.Integer)
	 */
	@Override
	public String updateSales(Integer id, String name, String phone, Integer projectid, Boolean isValid,
			Boolean isVanker) {
		Sales sale = saleDao.selectByPrimaryKey(id);
		if (sale == null)
			return "修改失败，数据异常";

		// 判断销售是否已存在
		Example example = new Example(Sales.class);
		example.createCriteria().andEqualTo("phone", phone).andEqualTo("deleted", false).andNotEqualTo("id", id);

		if (saleDao.selectCountByExample(example) > 0)
			return "修改失败，该销售人员手机已存在";

		int originProjectId = sale.getProjectid();
		sale.setName(name);
		sale.setPhone(phone);
		sale.setProjectid(projectid);
		sale.setUpdatedtime(CommonUtil.getTime());
		sale.setIsvalid(isValid);
		sale.setIsvanker(isVanker);
		if (originProjectId != projectid) {
			sale.setImgurl("");
			sale.setMediaid("");
		}
		int row = saleDao.updateByPrimaryKeySelective(sale);
		return row > 0 ? "ok" : "修改失败，数据异常";
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.SalesService#deleteSales(java.lang.Integer)
	 */
	@Override
	public String deleteSales(Integer id) {
		// TODO Auto-generated method stub
		Sales sale = saleDao.selectByPrimaryKey(id);
		if (sale == null)
			return "数据不存在";
		sale.setDeleted(true);
		int row = saleDao.updateByPrimaryKeySelective(sale);
		return row > 0 ? "ok" : "删除失败，数据异常";
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.SalesService#getSales(java.lang.Integer)
	 */
	@Override
	public Sales getSales(Integer id) {
		// TODO Auto-generated method stub
		return saleDao.selectByPrimaryKey(id);
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.SalesService#ExcelSales(java.lang.String,
	 * java.io.InputStream)
	 */
	@Override
	public String ExcelSales(String suffix, InputStream file) {
		ReadExcel readexcel = new ReadExcel();
		int row = 0;
		try {
			System.out.println("进入读取 excel");
			// 读取excel 内容
			List<ExcelSales_Vo> list = readexcel.readExcel(suffix, file);
			System.out.println("list:" + list.size());
			if (list != null && list.size() > 0) {
				for (ExcelSales_Vo sale : list) {

					Example example = new Example(Sales.class);
					example.createCriteria().andEqualTo("deleted", false).andEqualTo("phone", sale.getPhone());
					List<Sales> salelist = saleDao.selectByExample(example);
					if (salelist != null && salelist.size() > 0) {
						System.out.println("salelist:");
						Sales mysale = saleDao.selectByPrimaryKey(salelist.get(0).getId());
						mysale.setName(sale.getName());
						mysale.setProjectid(getProjectIdByName(sale.getProjectname()));
						saleDao.updateByPrimaryKeySelective(mysale);
					} else {
						Sales mysale = new Sales();
						mysale.setName(sale.getName());
						mysale.setPhone(sale.getPhone());
						mysale.setDeleted(false);
						mysale.setProjectid(getProjectIdByName(sale.getProjectname()));
						mysale.setUpdatedtime(CommonUtil.getTime());
						mysale.setIsvalid(true);
						mysale.setIsvanker(false);
						saleDao.insertSelective(mysale);
					}
					row++;
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		System.out.println("excelrows:" + row);
		return "ok_" + row;
	}

	// 根据项目名称获取项目id
	public Integer getProjectIdByName(String name) {
		if (Strings.isNullOrEmpty(name))
			return 0;
		Example example = new Example(Projects.class);
		example.createCriteria().andEqualTo("deleted", false).andEqualTo("name", name);
		List<Projects> list = projectDao.selectByExample(example);
		if (list != null && list.size() > 0) {
			return list.get(0).getId();
		} else {
			Projects project = new Projects();
			project.setName(name);
			project.setPostertempletid(0);
			project.setLat("");
			project.setLng("");
			project.setUpdatedtime(new Date());
			project.setDeleted(false);
			int row = projectDao.insertSelective(project);
			if (row > 0) {
				return project.getId();
			}
		}
		return 0;
	}

	@Override
	public Sales updateSalesOpenId(String phone, String openId) {
		Example example = new Example(Sales.class);
		example.createCriteria().andEqualTo("phone", phone);
		Sales sales = new Sales();
		sales.setWxopenid(openId);
		saleDao.updateByExampleSelective(sales, example);
		return sales;
	}

	/**
	 * 通过小程序openid获取销售，无效的或已删除的不会被获取。
	 */
	@Override
	public Sales getSaleByMiniOpenId(String miniOpenid) {
		Example example = new Example(Sales.class);
		example.createCriteria().andEqualTo("deleted", false).andEqualTo("isvalid", 1).andEqualTo("miniopenid",
				miniOpenid);
		List<Sales> list = saleDao.selectByExample(example);
		if (list.size() < 1)
			return null;
		return list.get(0);
	}

	@Override
	public Vo_msg updateSalesOpenId(String phone, String openId, String wxMiniCode) {
		Sales sales = null;
		try {
			Example example = new Example(Sales.class);
			example.createCriteria().andEqualTo("phone", phone).andEqualTo("deleted", false);

			List<Sales> list = saleDao.selectByExample(example);
			if (list != null && list.size() > 0) {
				sales = list.get(0);
				sales.setWxopenid(openId);
				sales.setMiniopenid(wxMiniCode);
				int row = saleDao.updateByPrimaryKeySelective(sales);
				// 生成海报图片
				if (row > 0) {
					// 绑定成功后将该销售的粉丝记录绑定的销售id清0
					Fans fans = fansService.getFansByMiniOpenid(wxMiniCode);
					if (fans != null) {
						Fans newfans = new Fans();
						newfans.setId(fans.getId());
						newfans.setSalesid(sales.getId());
						fansDao.updateByPrimaryKeySelective(newfans);
					}
					posterService.GeneratePosterJPG(sales.getId());
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return new Vo_msg(-1, "绑定失败，数据异常");
		}

		return new Vo_msg(0, sales);
	}

	@Override
	public List<Sales> getVankers() {
		Example example = new Example(Sales.class);
		example.createCriteria().andEqualTo("deleted", false).andEqualTo("isvalid", true).andEqualTo("isvanker", true);
		List<Sales> list = saleDao.selectByExample(example);
		if (list.size() < 1)
			return null;

		return list;
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.SalesService#CheckBinding(java.lang.String)
	 */
	@Override
	public String CheckBinding(String miniopenid) {
		System.out.println("miniopenid:" + miniopenid);
		if (Strings.isNullOrEmpty(miniopenid))
			return "";
		Example example = new Example(Sales.class);
		example.createCriteria().andEqualTo("deleted", false).andEqualTo("miniopenid", miniopenid);
		List<Sales> list = saleDao.selectByExample(example);
		String newurl = "";
		try {
			if (list != null && list.size() > 0) {
				String url = "http://mini.weiyisz.com/wx/chatListView?salesId=" + list.get(0).getId();
				newurl = wxOpenService.getWxMpService(RedisUtil.getMpAppid()).oauth2buildAuthorizationUrl(url,
						WxConsts.OAUTH2_SCOPE_BASE, URLEncoder.encode(""));
			}
		} catch (WxErrorException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("获取url异常");
		}
		System.out.println("已绑定的销售直接跳转客服面板：" + newurl);
		return newurl;
	}

	/*
	 * (非 Javadoc) Description:
	 * 
	 * @see com.theyeasy.dvmini.service.SalesService#getSalesReportList(int,
	 * java.lang.String)
	 */
	@Override
	public PageResults<SalesReport_Vo> getSalesReportList(int page, String keyword) {
		List<SalesReport_Vo> list = saleDao.getSalesReportList((page - 1) * 10, 10, keyword);
		int total = saleDao.getSalesReportCount(keyword);
		PageResults<SalesReport_Vo> pageResults = new PageResults<>();
		pageResults.setPage(page);
		pageResults.setRows(list);
		pageResults.setTotal(total);
		pageResults.setPageSize(10);
		return pageResults;
	}

	@Autowired
	ChatlogDao chatlogDao;

	@Override
	@Transactional
	public void transferSales2Sales(int salesId, int newSalesId, int fansId) {
		Example fansExample = new Example(Fans.class);
		Criteria criteria = fansExample.createCriteria().andEqualTo("salesid", salesId);
		if (fansId != 0) {
			criteria.andEqualTo("id", fansId);
		}
		List<Fans> fanses = fansDao.selectByExample(fansExample);

		Fans fans = new Fans();
		fans.setSalesid(newSalesId);
		fansDao.updateByExampleSelective(fans, fansExample);

		Example example = new Example(Chatlog.class);

		example.createCriteria().andEqualTo("salesid", salesId);
		if (fansId != 0) {
			example.createCriteria().andEqualTo("fansid", fansId);
		}
		Chatlog chatlog = new Chatlog();
		chatlog.setSalesid(newSalesId);
		chatlogDao.updateByExampleSelective(chatlog, example);
 
		Sales sales = getSales(salesId);
		Sales new_sales = getSales(newSalesId);
		for (Fans f : fanses) {
			chatlog = new Chatlog();
			//"【粉丝:" + f.getNickname() + "】由" + "【销售人员：" + salesId + "】转移到【销售人员" + newSalesId + "】"
			chatlog.setAsk("该粉丝从["+sales.getName()+"]转移以["+new_sales.getName()+"]");
			chatlog.setAskfrom(1);
			chatlog.setAsktime(new Date());
			chatlog.setFansid(f.getId());
			chatlog.setNoticetime(new Date());
			chatlog.setReaded(true);
			chatlog.setReadTime(new Date());
			chatlog.setReplytime(new Date());
			chatlog.setReplytype(ChatLogReplyType.提示信息.index);
			chatlog.setSalesid(newSalesId);
			chatlog.setVankerid(0);
			chatlogDao.insert(chatlog);
		}

	}

	
	@Override
	public String sendProudct(Integer projectId, Integer fansId) {
		Fans fans = fansService.getFansById(fansId);
		Projects project = projectService.getProject(projectId);
		return WxMiniUtil.sendCustoMiniprogrampage(fans.getMiniopenid(), project.getName(),
				"pages/index/index?id="+projectId,
				project.getPicurl(),
				project.getThumbMediaId());
	}
}
